package com.tinywind.Sword.Interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.auth0.jwt.interfaces.Claim;
import com.google.gson.Gson;
import com.tinywind.Sword.Dto.Result;
import com.tinywind.Sword.Utility.GaJJwtManager;
import com.tinywind.Sword.Utility.ResponseCodeManager;

public class TokenInterceptor implements HandlerInterceptor {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	// 之前
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String token = request.getHeader(GaJJwtManager.ms_authKey);
		String info = String.format("TokenIntercrept/preHandle1111,token is: %s", token);
		logger.info(info);
		logger.info("TokenIntecrept/preHandle2222,no token.");
		if (token == null) {
			logger.warn("TokenIntecrept/preHandle,no token.");
//			Result result = new Result(ResponseCodeManager.errorCode_noToken,ResponseCodeManager.errorMessage_noToken);
//			Gson gson = new Gson();
//			String str_result = gson.toJson(result);
//			response.getWriter().append(str_result);
//			response.getWriter().append("asdfasdasdfasdffasdf");
//			response.getWriter().flush();
			// 重定向返回登录失败信息.
			// 该方法只能用get请求来处理.
			response.sendRedirect(request.getContextPath() + "/User/NoToken?code=-100");

			return false;
		} else {
			Map<String, Claim> map = null;
			try {
				map = GaJJwtManager.verifyToken(token);
//				map = GaJJwtManager.parseToken(token);
			} catch (Exception e) {
				//过期
				logger.warn("token expired!");
				String url = String.format("%s/User/NoToken?code=%d",request.getContextPath(), ResponseCodeManager.errorCode_expiredToken);
				response.sendRedirect(url);
				return false;
			}
			Claim claim = map.get("userId");
			Integer userId = claim.asInt();
			info = String.format("TokenIntercrept/preHandle1111,user id is: %d", userId);
			request.setAttribute("userId", userId);
			logger.info(info);

		}
		return true;
	}

	// 执行后
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable ModelAndView modelAndView) throws Exception {
		String info = String.format("TokenIntercrept/postHandle");
		logger.info(info);
	}

	// 清理
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable Exception ex) throws Exception {
		String info = String.format("TokenIntercrept/afterCompletion");
		logger.info(info);
	}

}
